<template>
  <a-form
      :model="ruleForm"
      ref="ruleForm"
      v-bind="layout"
      :rules="rules"
      @finish="handleFinish">
    <a-form-item label="样品名称" name="sample_name">
      <a-input v-model:value="ruleForm.sample_name" />
    </a-form-item>
    <a-form-item label="合金代码" name="alloy_code">
      <a-select
        v-model:value="ruleForm.alloy_code"
        style="width: 120px"
        ref="select"
      >
        <a-select-option
          v-for="item in alloyCodeSelectionOptions"
          :key="item.url"
        >
          {{ item.label }}
        </a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="腐蚀电位" name="corrosion_potential">
      <a-input v-model:value="ruleForm.corrosion_potential" />
    </a-form-item>
    <a-form-item label="腐蚀电流" name="corrosion_current">
      <a-input v-model:value="ruleForm.corrosion_current" />
    </a-form-item>
    <a-form-item label="渗蚀度" name="permeability">
      <a-input v-model:value="ruleForm.permeability" />
    </a-form-item>
    <a-form-item label="钝化电流" name="passivation_current">
      <a-input v-model:value="ruleForm.passivation_current" />
    </a-form-item>
    <a-form-item label="极化曲线" name="polarization_curve">
      <a-upload
        :fileList="ruleForm.polarizationCurveFileList"
        :beforeUpload="beforePolarizationCurveUpload"
        :headers="headers"
        @change="handlePolarizationCurveChange"
      >
        <a-button>
          <upload-outlined />
          选择
        </a-button>
      </a-upload>
    </a-form-item>
    <a-form-item label="开路电位" name="open_circuit_potential">
      <a-input v-model:value="ruleForm.open_circuit_potential" />
    </a-form-item>
    <a-form-item label="开路电位曲线" name="open_circuit_potential_curve">
      <a-upload
        :fileList="ruleForm.openCircuitPotentialCurveFileList"
        :beforeUpload="beforeOpenCircuitPotentialCurveUpload"
        :headers="headers"
        @change="handleOpenCircuitPotentialCurveChange"
      >
        <a-button>
          <upload-outlined />
          选择
        </a-button>
      </a-upload>
    </a-form-item>
    <a-form-item label="腐蚀速率" name="corrosion_rate">
      <a-input v-model:value="ruleForm.corrosion_rate" />
    </a-form-item>
    <a-form-item label="热重曲线" name="thermogravimetric_curve">
      <a-upload
        :fileList="ruleForm.thermogravimetricCurveFileList"
        :beforeUpload="beforeThermogravimetricCurveUpload"
        :headers="headers"
        @change="handleThermogravimetricCurveChange"
      >
        <a-button>
          <upload-outlined />
          选择
        </a-button>
      </a-upload>
    </a-form-item>
    <a-form-item label="毒性" name="toxicity">
      <a-input v-model:value="ruleForm.toxicity" />
    </a-form-item>
    <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
      <a-button type="primary" :loading="submitting" html-type="submit">
        {{ submitting ? '提交中' : '确定' }}
      </a-button>
    </a-form-item>
  </a-form>
</template>
<script>
import { message } from 'ant-design-vue'
import { UploadOutlined } from '@ant-design/icons-vue'

export default {
  name: 'AddOrEditChemicalProperty',
  // url !== ''则为编辑操作，否则为添加
  props: ['url'],
  emits: ['operate-success', 'operate-failed'],
  components: {
    UploadOutlined,
  },
  data() {
    // validStr 不包含空格
    let validateAlloyName = async (rule, value) => {
      if (value === '') {
        return Promise.reject('请选择合金代码')
      }
    }
    return {
      ruleForm: {
        sample_name: '',
        alloy_code: '',
        corrosion_potential: '',
        corrosion_current: '',
        permeability: '',
        passivation_current: '',
        open_circuit_potential: '',
        corrosion_rate: '',
        toxicity: '',
        polarizationCurveFileList: [],
        openCircuitPotentialCurveFileList: [],
        thermogravimetricCurveFileList: [],
      },
      rules: {
        alloy_code: [
          {
            validator: validateAlloyName,
            trigger: 'change',
            required: true,
            whiteSpace: true,
          }
        ],
      },
      layout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 14 },
      },
      submitting: false,
      alloyCodeSelectionOptions: [],
      headers: {
        authorization: 'authorization-text',
      },
    }
  },
  mounted() {
    this.fetch()
  },
  methods: {
    // 从后端获取数据
    fetch() {
      // this.axios.get('http://127.0.0.1:8000/api/has_permission/', {
      //   permission: 'add_alloy_phase_diagram',
      // })
      this.alloyCodeSelectionOptions = []
      this.axios
        .get('/attachment_management/alloy_phase_diagram/')
        .then((res) => {
          const data = res.data
          for (let i = 0; i < data.length; ++i) {
            this.alloyCodeSelectionOptions.push({
              url: data[i].url,
              label: data[i].alloy_code,
            })
          }
          this.ruleForm.alloy_code = data.length === 0 ? '' : data[0].url
          if (this.url !== '') {
            this.axios
              .get(this.url)
              .then((res) => {
                const data = res.data
                this.ruleForm.sample_name = data.sample_name
                this.ruleForm.alloy_code = data.alloy_code
                this.ruleForm.corrosion_potential = data.corrosion_potential
                this.ruleForm.corrosion_current = data.corrosion_current
                this.ruleForm.permeability = data.erosion
                this.ruleForm.passivation_current = data.passivation_current
                this.ruleForm.open_circuit_potential =
                  data.open_circuit_potential
                this.ruleForm.corrosion_rate = data.corrosion_rate
                this.ruleForm.toxicity = data.toxicity
                // 若有附件，则装入列表
                if (data.polarization_curve_filename !== '') {
                  // console.log('not null')
                  this.ruleForm.polarizationCurveFileList.push({
                    uid: '-1',
                    name: data.polarization_curve_filename,
                  })
                }
                if (data.open_circuit_potential_curve_filename !== '') {
                  this.ruleForm.openCircuitPotentialCurveFileList.push({
                    uid: '-2',
                    name: data.open_circuit_potential_curve_filename,
                  })
                }
                if (data.tg_curve_filename !== '') {
                  this.ruleForm.thermogravimetricCurveFileList.push({
                    uid: '-3',
                    name: data.tg_curve_filename,
                  })
                }
              })
              .catch((error) => {
                console.log('Error', error.message)
              })
          }
        })
        .catch((error) => {
          console.log('Error', error.message)
          this.ruleForm.alloy_code = ''
        })
    },
    handleFinish(values) {
      this.submitting = true
      const {
        polarizationCurveFileList,
        openCircuitPotentialCurveFileList,
        thermogravimetricCurveFileList,
      } = this.ruleForm
      const formData = new FormData()
      formData.append('sample_name', values.sample_name)
      formData.append('alloy_code', values.alloy_code)
      formData.append('corrosion_potential', values.corrosion_potential)
      formData.append('corrosion_current', values.corrosion_current)
      formData.append('erosion', values.permeability)
      formData.append('passivation_current', values.passivation_current)
      formData.append('open_circuit_potential', values.open_circuit_potential)
      formData.append('corrosion_rate', values.corrosion_rate)
      formData.append('toxicity', values.toxicity)
      polarizationCurveFileList.forEach((file) => {
        // console.log(file.originFileObj)
        // console.log(file)
        // 若选择了文件，那么会有originFileObj属性，这种情况直接上传就可以，
        // 若无originFileObj属性，则说明是在编辑，且没有更改文件，文件列表中只有文件名而无文件实体，
        // 这个时候不传文件参数，让后端保持原文件不变
        if ('originFileObj' in file) {
          formData.append('polarization_curve', file.originFileObj)
        }
      })
      openCircuitPotentialCurveFileList.forEach((file) => {
        // console.log(file.originFileObj)
        if ('originFileObj' in file) {
          formData.append('open_circuit_potential_curve', file.originFileObj)
        }
      })
      thermogravimetricCurveFileList.forEach((file) => {
        // console.log(file.originFileObj)
        if ('originFileObj' in file) {
          formData.append('tg_curve', file.originFileObj)
        }
      })
      if (this.url !== '') {
        // 若文件列表为空，则附加属性通知后端
        if (this.ruleForm.polarizationCurveFileList.length === 0) {
          formData.append('polarization_curve_empty', true)
        }
        if (this.ruleForm.openCircuitPotentialCurveFileList.length === 0) {
          formData.append('open_circuit_potential_curve_empty', true)
        }
        if (this.ruleForm.thermogravimetricCurveFileList.length === 0) {
          formData.append('tg_curve_empty', true)
        }
        this.axios
          .put(this.url, formData)
          .then(() => {
            this.submitting = false
            message.success('修改成功！')
            this.$emit('operate-success')
          })
          .catch((error) => {
            this.submitting = false
            message.error('修改失败！')
            this.$emit('operate-failed')
            console.log('Error', error.message)
          })
      } else {
        this.axios
          .post('/property_management/chemical_property/', formData)
          .then(() => {
            this.submitting = false
            message.success('添加成功！')
            this.$emit('operate-success')
          })
          .catch((error) => {
            this.submitting = false
            message.error('添加失败！')
            this.$emit('operate-failed')
            console.log('Error', error.message)
          })
      }
    },
    beforePolarizationCurveUpload(file) {
      this.ruleForm.polarizationCurveFileList = [
        ...this.ruleForm.polarizationCurveFileList,
        file,
      ]
      return false
    },
    handlePolarizationCurveChange(info) {
      let fileList = [...info.fileList]
      // 取最后选择的文件
      // console.log('before:', fileList)
      fileList = fileList.slice(-1)
      // console.log('after:', fileList)
      this.ruleForm.polarizationCurveFileList = fileList
    },
    beforeOpenCircuitPotentialCurveUpload(file) {
      this.ruleForm.openCircuitPotentialCurveFileList = [
        ...this.ruleForm.openCircuitPotentialCurveFileList,
        file,
      ]
      return false
    },
    handleOpenCircuitPotentialCurveChange(info) {
      let fileList = [...info.fileList]
      // 取最后选择的文件
      fileList = fileList.slice(-1)
      this.ruleForm.openCircuitPotentialCurveFileList = fileList
    },
    beforeThermogravimetricCurveUpload(file) {
      this.ruleForm.thermogravimetricCurveFileList = [
        ...this.ruleForm.thermogravimetricCurveFileList,
        file,
      ]
      return false
    },
    handleThermogravimetricCurveChange(info) {
      let fileList = [...info.fileList]
      // 取最后选择的文件
      fileList = fileList.slice(-1)
      this.ruleForm.thermogravimetricCurveFileList = fileList
    },
  },
}
</script>
